Skip to content

Instantly share code, notes, and snippets.

@Osteri
Created May 27, 2017 04:50
Show Gist options
  • Save Osteri/ab9cc36f4274c6c523ae163a9a65b0e6 to your computer and use it in GitHub Desktop.
Save Osteri/ab9cc36f4274c6c523ae163a9a65b0e6 to your computer and use it in GitHub Desktop.
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dbg.h"
#include "queue.h"
#define CH_LEN 2 /* for storing char as str, for example: 'c' as {'c', '\0'} */
extern queue_t* parser_create(char* buf) {
char* str1 = buf; /* main token */
char* str2 = str1; /* sub token */
char str3[CH_LEN] = ""; /* store characters as strings */
char* ch_p1, *ch_p2, *ch_p3;
char* tok, *sub_tok;
int i;
queue_t* q = queue_create();
element_t e;
d_printf("Splitting string \"%s\" into tokens:\n", str1);
/* Split the buffer into tokens. */
for (i = 1; ; i++, str1 = NULL) {
tok = strtok_r(str1, " ", &ch_p1);
if (tok == NULL)
break;
d_printf("Token #%d: %s\n", i, tok);
/* Catch a command control character and turn it into a string. */
ch_p3 = strpbrk(tok, ":,");
if (ch_p3)
strncpy(str3, ch_p3, CH_LEN - 1);
/* Split tokens into subtokens. */
for (str2 = tok; ; str2 = NULL) {
sub_tok = strtok_r(str2, ":,", &ch_p2);
if (sub_tok == NULL)
break;
d_printf(" ~ subtoken \"%s\"\n", sub_tok);
/* Allocate memory and push into the queue. */
e = strdup(sub_tok);
if (e != NULL)
queue_push(q, e);
else
d_printf("String duplication \"strdup\" failed.\n");
if (ch_p3) {
d_printf(" ~ cmd char \"%s\"\n", str3);
/* Allocate memory and push into the queue. */
e = strdup(str3);
if (e != NULL)
queue_push(q, e);
else
d_printf("String duplication \"strdup\" failed.\n");
}
}
}
return q;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment